import Flutter
import UIKit
import AVFoundation

/// `SwiftFlutterAudioCapturePlugin` is a class that implements the Flutter plugin.
public class SwiftFlutterAudioCapturePlugin: NSObject, FlutterPlugin {
    /// `audioCaptureEventStreamHandler` is an instance of `AudioCaptureEventStreamHandler` used for handling audio capture events.
    private let audioCaptureEventStreamHandler = AudioCaptureEventStreamHandler()
    
    /// `register` is a method that registers the plugin with the Flutter engine.
    /// - Parameters:
    ///   - registrar: The registrar to register the plugin with.
    public static func register(with registrar: FlutterPluginRegistrar) {
        // 注册方法通道
        let methodChannel = FlutterMethodChannel(name: "ymd.dev/audio_capture_method_channel", binaryMessenger: registrar.messenger())
        let instance = SwiftFlutterAudioCapturePlugin()
        registrar.addMethodCallDelegate(instance, channel: methodChannel)
        
        // 注册事件通道
        let eventChannel = FlutterEventChannel(name: "ymd.dev/audio_capture_event_channel", binaryMessenger: registrar.messenger())
        eventChannel.setStreamHandler(instance.audioCaptureEventStreamHandler)
    }
    
    /// `handle` is a method that handles method calls from the Flutter side.
    /// - Parameters:
    ///   - call: The method call.
    ///   - result: The result to send back to the Flutter side.
    public func handle(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        switch call.method {
        case "init":
            // 初始化音频会话并请求权限
            initializeAudioSession(result: result)
        default:
            result(FlutterMethodNotImplemented)
        }
    }
    
    /// `initializeAudioSession` is a method that initializes the audio session and requests permission.
    /// - Parameters:
    ///   - result: The result to send back to the Flutter side.
    private func initializeAudioSession(result: @escaping FlutterResult) {
        // 检查麦克风权限
        AVAudioSession.sharedInstance().requestRecordPermission { [weak self] granted in
            if self == nil { return }
            
            if granted {
                // 用户授予了权限，初始化音频会话
                do {
                    // 预先设置音频会话，但不激活
                    // 实际激活将在开始录音时进行
                    let audioSession = AVAudioSession.sharedInstance()
                    try audioSession.setCategory(.record, mode: .default, options: [.duckOthers])
                    
                    // 返回成功
                    DispatchQueue.main.async {
                        result(true)
                    }
                } catch {
                    // 返回错误
                    DispatchQueue.main.async {
                        print("❌ 音频会话初始化失败: \(error)")
                        result(false)
                    }
                }
            } else {
                // 用户拒绝了权限
                DispatchQueue.main.async {
                    print("❌ 麦克风权限被拒绝")
                    result(false)
                }
            }
        }
    }
}